package com.kb.erp.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kb.erp.domain.PersonGradeInfo;
import com.kb.erp.entity.*;
import com.kb.erp.mapper.sqlServer.AttCardDataMapper;
import com.kb.erp.mapper.sqlServer.HrMapper;
import com.kb.erp.mapper.sqlServer.UpdateEmployeeLogsMapper;
import com.kb.erp.mapper.sqlServer.kbidm.PayAccountMapper;
import com.kb.erp.service.HrService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 业务字段 服务层实现
 *
 * @author
 */
@Service
@DS("hr")
@Slf4j
public class HrServiceImpl implements HrService {

    @Resource
    private HrMapper hrMapper;
    @Resource
    private AttCardDataMapper attCardDataMapper;
    @Resource
    private PayAccountMapper payAccountMapper;
    @Resource
    private UpdateEmployeeLogsMapper updateEmployeeLogsMapper;

    @Override
    public List<HrEntity> queryResignInfo(HrEntity hrEntity) {
        LambdaQueryWrapper<HrEntity> queryWrapper = null;
        List<HrEntity> hrEntityList;
        try {
            queryWrapper = Wrappers.lambdaQuery();
            //01 试用员工 02正式员工 04 离职员工
            queryWrapper.eq(HrEntity::getEmpCurrentStateNo, "04");
            if (!Objects.isNull(hrEntity.getLeaveStartDate())) {
                queryWrapper.ge(HrEntity::getLeaveDate, hrEntity.getLeaveStartDate());
            }
            if (!Objects.isNull(hrEntity.getLeaveEndDate())) {
                queryWrapper.le(HrEntity::getLeaveDate, hrEntity.getLeaveEndDate());
            }
            hrEntityList = hrMapper.selectList(queryWrapper);
        } catch (Exception e) {
            log.error("离职人员查询异常：{}", e.getMessage());
            throw new RuntimeException(e);
        }
        return hrEntityList;
    }

    @Override
    public List<AttCardData> queryAttCardData(Map map) {
        LambdaQueryWrapper<AttCardData> queryWrapper = Wrappers.lambdaQuery();
        List<String> empNoList = (List<String>) map.get("empNoList");
        queryWrapper.in(AttCardData::getEmpNo, empNoList);
        if (!Objects.isNull(map.get("startTime"))) {
            queryWrapper.ge(AttCardData::getYymmdd, map.get("startTime"));
        }
//        else {
//            //默认查今年
//            queryWrapper.ge(AttCardData::getYYMMDD,"2024-01-01");
//        }
        if (!Objects.isNull(map.get("endTime"))) {
            queryWrapper.le(AttCardData::getYymmdd, map.get("endTime"));
        }
        List<AttCardData> cardDataList = attCardDataMapper.selectList(queryWrapper);
        List<AttCardData> list = new ArrayList<>();
        for (AttCardData attCardData : cardDataList) {
            attCardData.setCardDate(DateUtil.formatDate(attCardData.getYymmdd()) + " " + attCardData.getCardTime());
            list.add(attCardData);
        }
        return list;
    }

    @Override
    public Page<PayAccount> queryBankCard(int page, int pageSize) {
        Page<PayAccount> payAccountPage = new Page<>(page, pageSize);
        return payAccountMapper.queryBankCard(payAccountPage);
    }

    @Override
    public Page<PerDepartInfo> queryDepartInfo(int page, int pageSize) {
        Page<PerDepartInfo> departInfo = new Page<>(page, pageSize);
        Page<PerDepartInfo> departInfoPage = payAccountMapper.queryPerDepartInfo(departInfo);
        List<PerDepartInfo> list = departInfoPage.getRecords();
        if (CollectionUtil.isNotEmpty(list)) {
            for (PerDepartInfo perDepartInfo : list) {
                if (StringUtils.isNotEmpty(perDepartInfo.getEmpNo2())) {
                    //empNo和empNo2 用,号拼接
                    perDepartInfo.setEmpNo(perDepartInfo.getEmpNo2() + "," + perDepartInfo.getEmpNo());
                    perDepartInfo.setMainMan(perDepartInfo.getEmpName2() + "," + perDepartInfo.getMainMan());
                }
                if (StringUtils.isNotEmpty(perDepartInfo.getEmpNo3())) {
                    perDepartInfo.setEmpNo(perDepartInfo.getEmpNo3() + "," + perDepartInfo.getEmpNo());
                    perDepartInfo.setMainMan(perDepartInfo.getEmpName3() + "," + perDepartInfo.getMainMan());
                }
            }
        }
        return departInfoPage;
    }

    /**
     * 删除同步异常的数据
     */
    @Override
    public void delUpdateEmployeeLogs() {
        LocalDateTime twoDaysAgo = LocalDateTime.now().minusDays(3);
        String formattedTwoDaysAgo = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").format(twoDaysAgo);

        // 构建更新条件
        UpdateWrapper<UpdateEmployeeLogsEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("Fstatus", "False").gt("CreateDate", formattedTwoDaysAgo);
        updateEmployeeLogsMapper.delete(updateWrapper);
    }

    @Override
    public List<HrEntity> queryByParams(String keyWord) {
        LambdaQueryWrapper<HrEntity> queryWrapper = Wrappers.lambdaQuery();
        //判断keyWord是数字
        if (keyWord.matches("\\d+")) {
            queryWrapper.eq(HrEntity::getEmpNo, keyWord);
        } else if
            //判断keyWord是中文
        (keyWord.matches("[\u4e00-\u9fa5]+")) {
            queryWrapper.eq(HrEntity::getEmpName, keyWord);
        } else {
            queryWrapper.eq(HrEntity::getEmpNo, keyWord);
        }
        return hrMapper.selectList(queryWrapper);
    }

    @Override
    public List<PersonGradeInfo> personGradeInfo() {
        List<PersonGradeInfo> hrEntities = hrMapper.personGradeInfo();
        if (CollectionUtil.isNotEmpty(hrEntities)) {
            for (PersonGradeInfo hrEntity : hrEntities) {
                String levelClass = hrEntity.getLevelClass(); // 比如 "12等"
                int level = 0;
                if (levelClass != null) {
                    // 使用正则表达式提取数字部分
                    String numberPart = levelClass.replaceAll("[^0-9]", "");
                    if (!numberPart.isEmpty()) {
                        level = Integer.parseInt(numberPart);
                    }
                }

                if (level >= 1 && level <= 12) {
                    hrEntity.setRemark("其余人员");
                } else if (level >= 13 && level <= 16) {
                    hrEntity.setRemark("副总及以上");
                } else if (level == 17) {
                    hrEntity.setRemark("总裁");
                } else {
                    hrEntity.setRemark("其余人员");
                }
            }
        }
        return hrEntities;
    }

    @Override
    public InvtInfo queryDeptByName(String name,String rkey) {
        List<HrEntity> hrEntities = hrMapper.queryDeptByName(name);
        if (hrEntities.size()>1){
            return null;
        }
        if (hrEntities.size() == 1) {
            HrEntity hrEntity = hrEntities.get(0);
            InvtInfo invtInfo = new InvtInfo();
            invtInfo.setUseName(hrEntity.getEmpName());
            invtInfo.setRkey(rkey);

            // 拼接 DtName2, DtName3, DtName4, DtName5
            List<String> deptNames = new ArrayList<>();
            if (Objects.nonNull(hrEntity.getDtName2())) {
                deptNames.add(hrEntity.getDtName2());
            }
            if (Objects.nonNull(hrEntity.getDtName3())) {
                deptNames.add(hrEntity.getDtName3());
            }
            if (Objects.nonNull(hrEntity.getDtName4())) {
                deptNames.add(hrEntity.getDtName4());
            }
            if (Objects.nonNull(hrEntity.getDtName5())) {
                deptNames.add(hrEntity.getDtName5());
            }
            if (Objects.nonNull(hrEntity.getDtName6())) {
                deptNames.add(hrEntity.getDtName6());
            }
            if (Objects.nonNull(hrEntity.getDtName7())) {
                deptNames.add(hrEntity.getDtName7());
            }
            if (!deptNames.isEmpty()) {
                String join = String.join("/", deptNames);
                invtInfo.setUseDept(join.substring(0, join.length() - 1));
            }
            return invtInfo;
        }
        return null;
    }

}